(function (window, undefined) {
    "use strict";
    layer.config({
        skin:'layer-ext-win8',
        extend:'skin/win8/style.css'
    });
    var events = {
        'open':[],
        'close':[],
        'min':[],
        'max':[]
    };
    var windows = {};
    var task = [];
    $(window.document).on('contextmenu',function (n){
        n=n?n:window.event;
        var t = n.srcElement?n.srcElement:n.target;
        return t.type=="text"||t.type=="textarea"?!0:!1
    });
    var log = function(tag,msg){
        if(window.console){
            if(typeof(msg) == "string"){
                console.log(tag + msg);return;
            }
            console.log(tag);
            console.log(msg);
        }
    }
    window.Logger = {
        priority:{
            info:3,
            debug:2,
            error:1
        },
        l:1,
        setPriority:function(l){
            this.l = l;
        },
        infoObject:function(obj){
            if(this.l >= this.priority.info) log('[info-object]',obj);
        },
        debug:function(msg){
            if(this.l >= this.priority.debug) log('[debug]',msg);
        },
        info:function(msg){
            if(this.l >= this.priority.info) log('[info]',msg);
        },
        error:function(msg){
            if(this.l >= this.priority.error) log('[error]',msg);
        }
    };
    function notification(){}
    notification.prototype = {
        /**
         * 轮询定时器
         */
        __notice__timer:null,
        __last_read:0,
        /**
         * 添加监听时间
         * @param func
         */
        notice:function(func){
            win.addEventHandler('notice_caller',func);
            return this;
        },
        /**
         * 开始读取消息
         * @param url
         * @param interval 时间间隔(单位:秒)
         * @returns {boolean}
         */
        start:function(interval){
            if(typeof(interval) != "number" || interval < 5){
                interval = 5;//读取消息间隔
            }
            interval = interval * 1000;//时间转换
            var _me = this;
            //使用ajax轮询消息
            var readNotice = function(){
                $.post('notification.notice',{prevRead:_me.__last_read},function(json){
                    if(json['code'] == 0){
                        _me.__last_read = json['data']['readTime'];
                        if(json['data']['count'] > 0){
                            win.triggerEvent('notice_caller','notice',json['data']['notices']);
                        }
                    }else{
                        if(json['code'] == '403'){
                            layer.msg(json['msg'],{time:2500,end:function(){
                                location.href = json['data'];
                            }});
                            return false;
                        }
                        Logger.debug(json['msg']);
                    }
                },'json').error(function(){Logger.error('read notice error');});
            };
            this.__notice__timer = setInterval(readNotice,interval);
            readNotice();
            return this;
        },
        /**
         * 停止消息的读取
         */
        stop:function(){
            if(this.__notice__timer != null){
                clearInterval(this.__notice__timer);
                this.__notice__timer = null;
            }
            return this;
        },
        read:function(id){
            $.get('notification.read?nid=' + id,function(text){
                Logger.debug(text);
            },'text').error(function(){
                    Logger.error('read failed');
                });
        }
    }
    var openedAppList = {};
    var win = {
        addEventHandler : function(type,func){
            if(typeof(events[type]) == "undefined"){events[type] = [];}
            if(typeof(func) == "function"){events[type].push(func);}
        },
        triggerEvent:function(type){
            if(typeof(events[type]) != "undefined" && events[type].length > 0){
                for(var i=0;i<events[type].length;i++){
                    if(typeof(events[type][i]) == "function"){
                        var args = [];
                        if(arguments.length > 1){
                            for(var j=1;j<arguments.length;j++){
                                args.push(arguments[j]);
                            }
                        }
                        try{events[type][i].apply(this,args);}
                        catch(e){}
                    }
                }
            }
        },
        open:function(url,config){
            var hashKey = $.md5(url);
            if(typeof(openedAppList[hashKey]) != "undefined"){
                var __app = openedAppList[hashKey];
                __app.show();
                __app.taskItem.addClass('twinkling');
                setTimeout(function(){
                    __app.taskItem.removeClass('twinkling');
                },2000);
                return openedAppList[hashKey];
            }
            var dom = null;
            var barItem = $('<span class="item task-bar-item"></span>').appendTo('#os_task_bar');
            var opts = $.extend({
                type: 2,
                area: ['700px', '500px'],
                fix: false, //不固定
//                moveType:1,
                shift:5,
                moveOut:true,
                maxmin: true,
                shade:false,
                content: url,
                title:'窗口',
                fullBottom:41,
                success:function(winObj,id){
                    dom = winObj;
                    Logger.debug(winObj);
                    layer.setTop(winObj);
                },
                end:function(){
                    if(typeof(openedAppList[hashKey]) != "undefined"){
                        delete openedAppList[hashKey];
                    }
                    barItem.remove();
                }
            },config);
            var index = layer.open(opts);
            barItem.attr('id','barItem_' + index);
            Logger.debug(index);
            var ret = {
                getDom:function(){return dom;},
                windowId:index,
                taskItem:barItem,
                close:function(){
                    layer.close(index);
                },
                setTitle:function(title){
                    layer.title(title, index);
                },
                getTitle:function(){
                    return opts.title;
                },
                show:function(){
                    if(dom){
                        if(!dom.is(":visible")) dom.show();
                        dom.css('z-index', layer.zIndex++ + 1);
                    }
                },
                hide:function(){
                    if(dom) dom.hide();
                },
                full:function(){
                    layer.full(index,{fullBottom:41});
                }
            };
            barItem.data('win',ret).html(opts.title).on('click',function(){
                if(dom){
                    if(dom.is(":visible")) ret.hide()
                    else ret.show();
                }
            });
            openedAppList[hashKey] = ret;
            return ret;
        },
        layoutDesktop:function(){
            var width = window.innerWidth,
                height = window.innerHeight - 41,
                item = {w:100,h:100},
                apps = $('.desktop').find('.app:visible'),
                count = apps.length;
            var maxRows = Math.floor(height / item.h),
                maxColumns = Math.ceil(count / maxRows);
            for(var i = 0;i < maxColumns;i ++){
                for(var j = 0;j < maxRows;j ++){
                    var index = i * maxRows + j;//获取当前设置的index
                    if(index >= count) return;
                    var _item = apps.eq(index),
                        _left = i * item.w,
                        _top = j * item.h;
                    _item.css({
                        left:_left,
                        top:_top
                    });
                }
            }
        },
        fullScreen:function(element) {
            if(element.requestFullscreen) {
                element.requestFullscreen();
            } else if(element.mozRequestFullScreen) {
                element.mozRequestFullScreen();
            } else if(element.webkitRequestFullscreen) {
                element.webkitRequestFullscreen();
            } else if(element.msRequestFullscreen) {
                element.msRequestFullscreen();
            }
        },
        notification:new notification(),
        notice:function(msg,notice,callback){
            if(typeof(notice['layer']) == "undefined" || notice['layer'] == false){
//                if (window.Notification && Notification.permission == 'granted'){
//                    var tilte = notice['notice_title'] ? notice['notice_title'] : '你有新信息';
//                    var ns = new Notification(tilte,{
//                        icon:ns_icon,
//                        body:notice['notice_message']
//                    });
//                    return;
//                }
            }
            var msgObj = $('.notification_wrapper').clone();
            msgObj.find('.content').html(msg);
            var index = layer.open({
                title: false,
                closeBtn: false,
                btn:false,
                shade: false,
                layout:{
                    right:'10px',
                    bottom:'50px',
                    left:'auto',
                    top:'auto'
                },
                tipsMore: true,
                shift: 2,
                // type:1,
                topIndex:99999,
                skin: 'notice-wrapper',
                content: msgObj,
                end: function(){
                    if(typeof(callback) == "function") callback.call(this,index);
                }
            });
            msgObj.find('.msg-close').on('click',function(){
                layer.close(index);
                return false;
            }).parents('.layui-layer').css('border','none');
            msgObj.find('[data-notice]').attr('data-notice',notice['nid']);
        }
    }

    window.osw = win;
})(window);
